package com.ajx.blog.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.ajx.blog.entity.CourseInfo;
import com.ajx.blog.service.api.CourseInfoService;
import com.ajx.blog.util.FileUtil;
import com.github.pagehelper.PageInfo;

import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/blog/course/root")
public class CourseController {

    private Logger logger = LoggerFactory.getLogger(CourseController.class);

    @Reference(url = "dubbo://localhost:20882")
    private CourseInfoService courseInfoService;

    /**
     * @param {MultipartFile} imgurl 课程图片
     * @param {CourseInfo}    courseInfo 课程对象
     * @return {Object}
     * 
     * @description: 添加一门课程
     */
    @PostMapping
    public Object insertOneCourse(@RequestParam(value = "imgurl", required = false) MultipartFile imgurl,
            CourseInfo courseInfo)
            throws FileNotFoundException {
        logger.info("管理员调用insertOneCourse()方法");
        Map<String, Object> returnMap = new HashMap<>();
        courseInfo.setCourseImage("/");
        courseInfo.setPersonNumber(0);
        if (imgurl != null && imgurl.getSize() > 0) {// 文件上传
            // 原文件名
            String submittedFileName = imgurl.getOriginalFilename();
            String fileName = FileUtil.getFileName(submittedFileName);
            // 获取文件上传路径
            String realPath = ResourceUtils.getURL("classpath:").getPath();
            String datePath = FileUtil.getFileDatePath();
            String filePath = realPath + "/static/upload/" + datePath;
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            if (!imgurl.isEmpty()) {
                try (FileOutputStream fos = new FileOutputStream(filePath + "/" + fileName);
                        InputStream in = imgurl.getInputStream();) {
                    int b = 0;
                    while ((b = in.read()) != -1) {
                        fos.write(b);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            courseInfo.setCourseImage("upload/" + datePath + "/" + fileName);
        }
        if (courseInfoService.insertOneCourse(courseInfo)) {
            returnMap.put("code", 0);
            returnMap.put("msg", "管理员添加课程成功");
            logger.info("管理员添加课程成功");
        } else {
            returnMap.put("code", -1);
            returnMap.put("msg", "管理员添加课程失败");
            logger.info("管理员添加课程失败");
        }
        return returnMap;
    }

    /**
     * @param {CourseInfo} courseInfo 待更新的课程对象
     * @return {Object}
     * 
     * @description: 更新一门课程信息
     */
    @PutMapping
    public Object updateCourse(@RequestBody CourseInfo courseInfo) {
        logger.info("管理员调用updateCourse()方法");
        Map<String, Object> returnMap = new HashMap<>();
        if (courseInfoService.updateOneCourse(courseInfo)) {
            returnMap.put("code", 0);
            returnMap.put("msg", "管理员更新指定课程成功");
            logger.info("管理员更新指定课程成功");
        } else {
            returnMap.put("code", -1);
            returnMap.put("msg", "管理员更新指定课程失败");
            logger.info("管理员更新指定课程失败");
        }
        return returnMap;
    }

    /**
     * @param {Integer} page 当前页码数
     * @param {Integer} pageSize 当前记录数
     * @return {Object}
     * 
     * @description: 获取分页后的课程集合
     */
    @GetMapping("/{page}")
    public Object getAllCourseByLimit(@PathVariable(value = "page") Integer page,
            @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        logger.info("管理员调用getAllCourseByLimit()方法");
        Map<String, Object> returnMap = new HashMap<>();
        PageInfo<CourseInfo> info = courseInfoService.selectCourseList(page, pageSize);
        returnMap.put("code", 0);
        returnMap.put("data", info);
        returnMap.put("msg", "管理员分页查询课程列表成功");
        logger.info("管理员分页查询课程列表成功");
        return returnMap;
    }

    /**
     * @param {Integer} courseId 课程ID
     * @return {Object}
     * 
     * @description: 通过课程ID获取指定课程
     */
    @GetMapping(value = "/one/{courseId}")
    public Object getCourseById(@PathVariable(value = "courseId") Integer courseId) {
        logger.info("管理员调用getCourseById()方法");
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("code", 0);
        returnMap.put("data", courseInfoService.selectCourseById(courseId));
        returnMap.put("msg", "管理员通过课程ID查询指定课程成功");
        logger.info("管理员通过课程ID查询指定课程成功");
        return returnMap;
    }

    /**
     * @param {Integer} courseId 课程编号
     * @param {Integer} page 当前页码数
     * @return {Object}
     * 
     * @description:通过分页数据和当前页码数查询选了此门课程的用户集合
     */
    @GetMapping(value = "/userInCourse/{courseId}/{page}")
    public Object getUserListInCourse(@PathVariable(value = "courseId") Integer courseId,
            @PathVariable(value = "page") Integer page) {
        logger.info("管理员调用getUserListInCourse()方法");
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("code", 0);
        returnMap.put("data", courseInfoService.selectUserListByCourseId(courseId, page));
        returnMap.put("msg", "管理员通过课程ID查询选课用户列表成功");
        logger.info("管理员通过课程ID查询选课用户列表成功");
        return returnMap;
    }

}
